﻿using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using EvoGame.Core.Components;
using EvoGame.Core.Helpers;
using EvoGame.Core.Interfaces;

namespace EvoGame.Core.Files
{
	public static partial class FileHandler
	{
		public class Licence : File, ILoadable
		{
			protected override sealed FileStream fileStream
			{
				get
				{
					try
					{
						return this.file.Open (FileMode.Open, FileAccess.Read, FileShare.Read);
					}
					catch (IOException e)
					{
						if (EvoApp.Debug)
							EvoApp.Debug.Output = "Licence file not found: " + e;
						Directory.CreateDirectory (file.DirectoryName);
						return this.file.Open (FileMode.CreateNew);
					}
				}
			}

			private XmlReader xmlRead;
			private XElement licence;

			public Licence()
				: base (String.Format ("{0}{1}EvoGame{1}licence.evo", Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments), System.IO.Path.DirectorySeparatorChar))
			{
				this.xmlRead = XmlReader.Create(fileStream);
			}

			public void Load()
			{
				try
				{
					this.licence = XDocument.Load(xmlRead).Root.Element(EvoApp.Name);
				}
				catch (Exception e)
				{
					if (EvoApp.Debug) EvoApp.Debug.Output = "Error loading Licence file: " + e;
				}
			}

			public bool IsValid()
			{
				try
				{
					string user = this.licence.Element("User").Value;
					string id = this.licence.Element("ID").Value;
					string hash = Helper.HashString(user + EvoApp.Name);
					if (id == hash)
					{
						EvoApp.SetUser(user);
						return true;
					}
					else if (id == "")
					{
						EvoApp.SetUser (user);
					}
					else
					{
						if (EvoApp.Debug) EvoApp.Debug.Output = "Licence file invalid";
					}
				}
				catch
				{
				}
				return false;
			}

			public override void Close()
			{
				this.xmlRead.Close();
				this.fileStream.Close();
			}
		}
	}
}